var express = require('express');
var router = express.Router();
const db = require("../db/db");
var multer = require('multer');
 //导入连个内置模块
const path= require('path')
const fs=require('fs')
var objMulter=multer({dest: './public/images'}); 
router.use(objMulter.any());  
/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

//插入地区疫情数据接口
router.get("/inset", (req, res) => {
  request("http://route.showapi.com/2217-5?showapi_appid=1084431&showapi_sign=52c2e1c6b19e426382d45cf073be6873", (err, response, body) => {
    if (err) {
      throw err
    } else {
      let data = JSON.parse(body).showapi_res_body.foreignList;
      var str = "";
      data.forEach(item => {
        str += `(null,"${item.areaName}","${item.deadNum}","${item.curedNum}"),`

      });
      str = str.substring(0, str.length - 1);
      console.log(str);
      // var str = `(null,"1111","111","111"),(null,"1111","111","111"),(null,"1111","111","111")`
      var sql = `INSERT INTO world VALUES ${str}`;

      db(sql, (err, result) => {
        if (err) {
          throw err;
        }
        let data = {
          mes: "插入成功",
          code: 1,
          data: result
        }
        res.json(data)
      })
    }
  })

})

router.get("/search", (req, res) => {
  let sql = "select * from world";
  db(sql, (err, result) => {
    res.json(result)
  })
})
// 写一个上传图片的接口
router.post('/upload',function(req,res,next){
  // console.log(req.body,req.files)
  req.files.forEach(item => {
      let oldPath = item.path;
      let newPath = "./public/images/" + item.originalname;
      fs.renameSync(oldPath,newPath);
      console.log(newPath);
  });
  res.send({
      code:1,
      msg:'成功',
  })
})

module.exports = router;
